package com.sencorsta.ids.talk.OpenHandler;

import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.*;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessageHandler;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.talk.proto.ImtalkMemberSiroSettingByProto;
import com.sencorsta.ids.talk.proto.ImtalkPushGroupUpdateMsg;
import com.sencorsta.ids.talk.proto.ImtalkPushMessageByProto;
import com.sencorsta.utils.date.DateUtil;
import io.netty.channel.Channel;

import java.util.ArrayList;
import java.util.List;

/**
* @description: 群成员权限修改
* @author TAO
* @date 2019/7/15 19:32
*/
@ClientEvent("MemberSiroSetting")
public class MemberSiroSetting extends OpenMessageHandler implements RedisService {
    @Override
    public RpcMessage request(Channel channel, JSONObject json, String content, byte[] data, byte[] protobuf) {
        Out.info("----------------------群成员权限修改MemberSiroSetting--------------------------");
        ImtalkMemberSiroSettingByProto.MemberSiroSettingRes.Builder res=ImtalkMemberSiroSettingByProto.MemberSiroSettingRes.newBuilder();

        //服务器推的群状态跟新
        ImtalkPushGroupUpdateMsg.PushGroupUpdate.Builder pushUpdate= ImtalkPushGroupUpdateMsg.PushGroupUpdate.newBuilder();

        //服务器推送的消息
        ImtalkPushMessageByProto.PushMsg.Builder pushsys= ImtalkPushMessageByProto.PushMsg.newBuilder();
        try{

            ImtalkMemberSiroSettingByProto.MemberSiroSettingReq req=ImtalkMemberSiroSettingByProto.MemberSiroSettingReq.parseFrom(protobuf);
            res.setSign(req.getSign());

            //被修改者
            List<String> tagIdList=req.getTagIdList();

            Out.debug("tagIdList----------------------------"+tagIdList);
            if (tagIdList==null){
                return responseProto( res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.TAGID_IS_NULL)));
            }

            //修改类型
            int type=req.getType();

            //修改数据
            String _data=req.getData();

            //群id
            String groupId=req.getGroupId();

            //发起者的详情信息
            JSONObject userInfo= JSONObject.parseObject((R_GROUP.hget(groupId,userId)));
            Out.debug("发起者的详情信息"+userInfo);

            //定义系统消息
            JSONObject msg=new JSONObject();

            Boolean sign=true;

            if (type==1){//1.群主转让---只有群主能设置------1
                Out.debug("------------------群主转让---只有群主能设置");
                //发起者权限判断------只有群主能设置
                if (!"1".equals(String.valueOf(userInfo.get("adminType")))){
                    return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.JURISDICTION_INSUFFICIENT)));
                }

                //取出目标Id
                String tagId=tagIdList.get(0);

                //得到目标用户的详情信息
                JSONObject tagInfo= JSONObject.parseObject((R_GROUP.hget(groupId,tagId)));
                //权限替换
                tagInfo.put("adminType",1);
                userInfo.put("adminType",3);
                //修改
                R_PROPERTY.hset(groupId,"main",tagId);
                //获取消息内容
                msg.put("msgContent",userInfo.get("nickname")+"将群主转让"+tagInfo.get("nickname")+"\n\n");
                //内容类型 1.文字 2.图片  等等...--0.系统消息
                msg.put("msgType",1004);
                R_GROUP.hset(groupId,userId, String.valueOf(userInfo));//保存自己的
                //将修改的数据保存
                R_GROUP.hset(groupId,tagId, String.valueOf(tagInfo));//保存目标的
            }else if(type==2){//2.设置管理员---只有群主能设置------n
                Out.info("------------------设置管理员---只有群主能设置");

                if (!"1".equals(String.valueOf(userInfo.get("adminType")))){
                    Out.debug("=============权限不够=======================");
                    return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.JURISDICTION_INSUFFICIENT)));
                }
                //创建目标详情的集合
                List<JSONObject> tagInfoList=new ArrayList<JSONObject>();
                String tagnickname="";
                String text="";
                for (int i=0;i<tagIdList.size();i++){
                    tagInfoList.add(JSONObject.parseObject((R_GROUP.hget(groupId,tagIdList.get(i)))));
                    Out.debug("---------adminType-------"+String.valueOf(tagInfoList.get(i).get("adminType")));
                    if ("3".equals(String.valueOf(tagInfoList.get(i).get("adminType")))){
                        tagInfoList.get(i).put("adminType",2);
                        Out.debug("------------------------------设置为管理员--------------------------");
                        text="设置为管理员";
                    }else if("2".equals(String.valueOf(tagInfoList.get(i).get("adminType")))){
                        tagInfoList.get(i).put("adminType",3);
                        Out.debug("------------------------------解除管理员--------------------------");
                        text="解除管理员";
                    }
                    //将修改的数据保存
                    R_GROUP.hset(groupId,tagIdList.get(i), String.valueOf(tagInfoList.get(i)));//保存目标的
                    tagnickname+= String.valueOf(tagInfoList.get(i).get("nickname"))+"\n";
                }
                Out.debug("tagInfoList-------------"+tagInfoList);
                //获取消息内容
                msg.put("msgContent",userInfo.get("nickname")+"将"+tagnickname+text+"\n\n");
                //内容类型 1.文字 2.图片  等等...--0.系统消息
                msg.put("msgType",1005);
            }else if(type==3){//3.修改禁言---群主管理员都能--------n
                Out.debug("------------------修改禁言---群主管理员都能");
                if ("3".equals(String.valueOf(userInfo.get("adminType")))) {//等于3为平民
                    return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.JURISDICTION_INSUFFICIENT)));
                }
                //创建目标详情的集合
                List<JSONObject> tagInfoList=new ArrayList<JSONObject>();
                String tagnickname="";
                String text="";
                for (int i=0;i<tagIdList.size();i++){
                    tagInfoList.add(JSONObject.parseObject((R_GROUP.hget(groupId,tagIdList.get(i)))));
                    if (_data.equals("1")){
                        tagInfoList.get(i).put("silent",0);
                        text="禁言";
                    }else{
                        tagInfoList.get(i).put("silent",1);
                        text="解除禁言";
                    }
                    tagnickname+= String.valueOf(tagInfoList.get(i).get("nickname"))+"\n";
                    //将修改的数据保存
                    R_GROUP.hset(groupId,tagIdList.get(i), String.valueOf(tagInfoList.get(i)));//保存目标的
                }
                //获取消息内容
                msg.put("msgContent",userInfo.get("nickname")+"将"+tagnickname+text+"了"+"\n\n");
                //内容类型 1.文字 2.图片  等等...--0.系统消息
                msg.put("msgType",1006);
            }else if(type==4){//4..修改成员本群昵称----无需判断权限----1
                Out.debug("------------------1.修改成员本群昵称----无需判断权限");
                userInfo.put("nickname",_data);
                //将修改的数据保存
                R_GROUP.hset(groupId,userId, String.valueOf(userInfo));//保存自己的
                sign=false;
            }

            //得到群成员列表
            Object[] memberList = R_GROUP.hkeys(groupId).toArray();

            Out.debug("groupId"+groupId);
            Out.debug("得到群成员列表---------------------"+memberList);

            pushUpdate.setGroupId(groupId);//群聊id
            for (int i=0;i<memberList.length;i++){
                Out.debug("----------------groupUpdate-------------------");
                MsgService.pushAndSavedUnique(pushProto(String.valueOf(memberList[i]),"push.groupUpdate",pushUpdate),"push.groupUpdate-"+groupId);
            }

            if (sign) {//当sign为4  修改个人本群的昵称是不推
                msg.put("srcId","0");
                //获取目标用户id
                msg.put("tagId", groupId);
                //获取消息类型1.单发  2.群发
                msg.put("tagType", 2);
                //消息时间
                msg.put("time", DateUtil.getDateTime());
                //添加Redis的消息库中
                String msgId = IdService.newMsgId();
                R_MESSAGES.set(msgId, msg.toJSONString());

                pushsys.setUserId(groupId);
                pushsys.setMsgId(msgId);

                //AuroraPush.pushAurora(msgId);//极光推送
                //系统推送消息
                for (Object receiver : memberList) {
                    MsgService.pushAndSaved(pushProto(String.valueOf(receiver), "push.Msg", pushsys));
                }
            }
            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SUCCESS));
            return responseProto(res);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
            return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SERVER_ERROR)));
        }
    }
}



